﻿#include "TableReadColFunction.h"

#include <QDebug>

#include "DoubleVector.h"
#include "TableInSceneWidget.h"
#include "TableInSceneModel.h"

class TableReadColFunction::TableReadColFunctionPrivate :QObject
{
public:
	int in_params[16];
	int out_params[1];
	int in_count;
	int out_count;
public:
	TableReadColFunctionPrivate(QObject*parent) :QObject(parent)
	{
		in_count = 2;
		out_count = 1;

		in_params[0] = FPT_PTR;
		in_params[1] = FPT_STRING_OR_NUMBER;//FPT_NUMBER | 
		out_params[0] = FPT_VECTOR;
	}

};

TableReadColFunction::TableReadColFunction(QObject *parent)
	: QObject(parent),private_ptr(new TableReadColFunctionPrivate(this))
{
}

TableReadColFunction::~TableReadColFunction()
{
}

static int TableReadColFunction_FUNCTION(struct variant_s *in, int in_count, struct variant_s *out, void*tag)
{
	if (2 != in_count)
		return ERR_PARAM_NOT_MATCH;

	// 判断第一个参数
	if (VALUETYPE_VOID_PTR != in[0].type)
		return ERR_DATATYPE_NOT_MATCH;
	if (nullptr == in[0].u.ptr)
		return ERR_DATATYPE_NOT_MATCH;

	// 判断第二个参数
	int col = -1;
	switch (in[1].type) {
	case VALUETYPE_DOUBLE:
		col = (int)in[1].u.d;
		break;
	case VALUETYPE_INTEGER:
		col = in[1].u.i;
		break;
	case VALUETYPE_STRING:
		break;
	default:
		return ERR_DATATYPE_NOT_MATCH;
	}

	AstScene*as = nullptr;
	TableInSceneWidget*ptr = nullptr;
	try {
		as = (AstScene*)in[0].u.ptr;
		ptr = dynamic_cast<TableInSceneWidget*>(as->widget());
		//doc = ptr->textDocument();
	}
	catch (...) {
		//doc = nullptr;
	}

	if (!ptr)
		return -1;

	TableInSceneModel*m = ptr->model();

	BaseVector*v = new BaseVector(nullptr);

	m->readColData(col, v->data());

	out->type = VALUETYPE_ARRAY;// VALUETYPE_DOUBLE_VECTOR;
	out->u.ptr = (IVector*)v;
	out->fn_addref = BaseVector::addref_fn;
	out->fn_release = BaseVector::release_fn;

	//qDebug() << "double vector:" << out->u.ptr << ", fn:" << addref_doublevector << "," << release_doublevector;

	return 0;
}

AstFunction* TableReadColFunction::operator()()
{
	return dynamic_cast<AstFunction*>(this);
}

QString TableReadColFunction::name()
{
	return "TableReadCol";
}
int* TableReadColFunction::outputTypes()
{
	return private_ptr->out_params;
}
int TableReadColFunction::outputCount()
{
	return private_ptr->out_count;
}
int* TableReadColFunction::inputTypes()
{
	return private_ptr->in_params;
}
int TableReadColFunction::inputCount()
{
	return private_ptr->in_count;
}
void* TableReadColFunction::function()
{
	return TableReadColFunction_FUNCTION;
}
